package com.timeDeal.util;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**数据库链接使用
 * Created by 叼爸爸 on 2016/8/31.
 */
public class DButil {
    /**
     * 连接池链接数据库
     *
     * @return
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            Context ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/timedeal");
            conn = ds.getConnection();
            return conn;
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 获取给定表的主键的最大值
     *
     * @param pkname
     * @param tablename
     * @return
     */
    public static int getZhuJianMax(String pkname, String tablename) {
        String sql = "";
        int result = 0;
        PreparedStatement ps = null;
        ResultSet rs = null;
        sql = "SELECT IFNULL(MAX(" + pkname + "),0)+1 FROM " + tablename;
        Connection conn = getConnection();
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            if (rs.next()) {
                result = rs.getInt(1);
            } else {
                result = 1;
            }
        } catch (SQLException e) {
            e.printStackTrace();

        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


        return result;
    }
}
